<?php

class CommonAction extends Action
{

    protected function  getData($tables, $fields, $condition = array())
    {
        $model = M($tables);
        $data = $model->field($fields)->where($condition)->select();
        return $data;

    }

    protected function  ReformateData($tables, $ParentID, $indentfield, $condition = array())
    {
        $model = M($tables);
        $condition["parentid"] = $ParentID;
        $data = $model->where($condition)->select();

        $temp = array();


        foreach ($data as $k => &$v)
        {
            $prefix = '';
            $sortpath = trim($v["path"]);
            if (substr($sortpath, -1) == ',') $sortpath = substr($sortpath, 0, -1);


            $path_arr = explode(",", $sortpath);
            $pathlen = count($path_arr);
            for ($i = 0; $i < $pathlen - 2; $i++) //--------2是因为后边有一个多余的,前面公有的是0
            {
                $prefix .= "│&nbsp;";
            }
            $v[$indentfield] = $prefix . '├' . $v[$indentfield];
            $child = $this->ReformateData($tables, $v['id'], $indentfield, $condition);
            if ($child) $v["child"] = 1;
            $temp[] = $v;
            foreach ($child as $kc => $vc) $temp[] = $vc;
        }

        return $temp;

    }

    protected function  InitClassSelectOption($tables, $ParentID, $ChkID)
    {

        $str = "";
        $model = M($tables);
        $condition["parentid"] = $ParentID;
        $data = $model->where($condition)->select();
        $template = '<option value="%d" %s >%s</option>';

        foreach ($data as $k => $v)
        {
            $checked = '';
            $prefix = '';
            $sortpath = trim($v["path"]);
            if (substr($sortpath, -1) == ',')
            {
                $sortpath = substr($sortpath, 0, -1);
            }

            $path_arr = explode(",", $sortpath);
            $pathlen = count($path_arr);
            for ($i = 0; $i < $pathlen - 2; $i++) //--------2是因为后边有一个多余的,前面公有的是0
            {
                $prefix .= "│&nbsp;";
            }
            if ($ChkID == $v['id'])
            {
                $checked = 'selected="selected"';
            }
            $str .= sprintf($template, $v['id'], $checked, $prefix . '├' . $v["name"]);
            $str .= $this->InitClassSelectOption($tables, $v['id'], $ChkID);

        }

        return $str;
    }

    public $loginMarked;

    /**
     * +----------------------------------------------------------
     * 初始化
     * 如果 继承本类的类自身也需要初始化那么需要在使用本继承类的类里使用parent::_initialize();
     * +----------------------------------------------------------
     */
    public function _initialize()
    {

        header("Content-Type:text/html; charset=utf-8");
        $systemConfig = include WEB_ROOT . 'Common/systemConfig.php';
        $this->loginMarked = md5($systemConfig['TOKEN']['admin_marked']);
        // echo "this is common initialize";exit();

        $this->checkLogin();

        //TODO:这里变成缓存,这样读太费资源
        $myinfo = I("session.my_info");
        if (!$myinfo)
        {
            redirect("Index/logout", 2, "登录超时");
        }
        $isleader = $myinfo["isleader"];
        $department = $myinfo["department"];

        $departmodel = M("department");
        if ($isleader)
        {
            //管理的部门列表,然后取出员工列表
            $condition["path"] = array("exp", "like '%," . $department . ",%'");
            $departdata = $departmodel->field("id")->where($condition)->select();
            $alldepart = "";
            $alluser = "";

            foreach ($departdata as $k => $v)
                $alldepart .= $v["id"] . ",";
            $alldepart = substr($alldepart, 0, -1);

            $employeemodel = M("employee");
            $empcon["department"] = array("exp", "in ($alldepart)");
            $chargeemployee = $employeemodel->where($empcon)->select();

            if ($chargeemployee)
            {
                foreach ($chargeemployee as $k => $v)
                    $alluser .= $v["id"] . ",";
            }
            $alluser = substr($alluser, 0, -1);

            session("isleader", 1);
            session("department", $alldepart);
            session("employee", $alluser);
        } else
        {
            session("isleader", 0);
        }


        $this->assign("menu", $this->show_menu());
        $this->assign("sub_menu", $this->show_sub_menu());
        $this->assign("my_info", $_SESSION['my_info']);
        $this->assign("site", $systemConfig);

    }

    public function CacheArray($tablename, $idfields = 'id', $condition = array())
    {

        $type = M($tablename);
        $data = $type->where($condition)->order('id asc')->select();
        foreach ($data as $k => $v)
            $list[$v[$idfields]] = $v;
        return $list;
    }


    public function cache_clear()
    {
        $this->deldir(TEMP_PATH);
    }

    function deldir($dir)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh))
            if ($file != "." && $file != "..")
            {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath))
                {
                    unlink($fullpath);
                } else
                {
                    deldir($fullpath);
                }
            }

    }

    /*
 * 邮件发送
 * @param string $to 收件人邮箱，多个邮箱用,分开
 * @param string $mailfrom 发件人邮箱
 * @param string $title 标题
 * @param string $content 内容
 */

    public function email($to, $mailfrom, $mailtitle, $mailbody)
    {
        import("@.ORG.Util.mail"); //导入邮件类，在附件里面
        //邮件相关变量
        $cfg_smtp_server = 'smtp.qq.com';
        $cfg_ask_guestview = '8';
        $cfg_smtp_port = '25';
        $cfg_ask_guestanswer = '8';
        $cfg_smtp_usermail = '2355621408@qq.com'; //你的QQ邮箱
        $cfg_smtp_user = '2355621408'; //你的QQ号
        $cfg_smtp_password = '@YiShang888'; //你的QQ密码

        $smtp = new smtp($cfg_smtp_server, $cfg_smtp_port, true, $cfg_smtp_usermail, $cfg_smtp_password);
        $smtp->debug = false;

        //$to 多个邮箱用,分隔
        $mailtype = 'TXT';
        $smtp->sendmail($to, $mailfrom, $cfg_smtp_usermail, $mailtitle, $mailbody, $mailtype);
    }


    protected function getQRCode($url = NULL)
    {
        if (IS_POST)
        {
            $this->assign("QRcodeUrl", "");
        } else
        {
//            $url = empty($url) ? C('WEB_ROOT') . $_SERVER['REQUEST_URI'] : $url;
            $url = empty($url) ? C('WEB_ROOT') . U(MODULE_NAME . '/' . ACTION_NAME) : $url;
            import('QRCode');
            $QRCode = new QRCode('', 80);
            $QRCodeUrl = $QRCode->getUrl($url);
            $this->assign("QRcodeUrl", $QRCodeUrl);
        }
    }

    public function checkLogin()
    {
        if (isset($_COOKIE[$this->loginMarked]))
        {
            $cookie = explode("_", $_COOKIE[$this->loginMarked]);
            $timeout = C("TOKEN");
            if (time() > (end($cookie) + $timeout['admin_timeout']))
            {
                setcookie("$this->loginMarked", NULL, -3600, "/");
                unset($_SESSION[$this->loginMarked], $_COOKIE[$this->loginMarked]);
                $this->error("登录超时，请重新登录", U("Public/index"));
            } else
            {
                if ($cookie[0] == $_SESSION[$this->loginMarked])
                {
                    setcookie("$this->loginMarked", $cookie[0] . "_" . time(), 0, "/");
                } else
                {
                    setcookie("$this->loginMarked", NULL, -3600, "/");
                    unset($_SESSION[$this->loginMarked], $_COOKIE[$this->loginMarked]);
                    $this->error("请重新登录", U("Public/index"));
                }
            }
        } else
        {
            $this->redirect("Public/index");
        }
        return TRUE;
    }


    public function  logout()
    {
        setcookie("$this->loginMarked", NULL, -3600, "/");
        unset($_SESSION["$this->loginMarked"], $_COOKIE["$this->loginMarked"]);
        session_destroy();
        $this->assign("jumpUrl", U('Public/index/'));
        $this->success('登出成功！');


    }

    public function AjaxHead()
    {
        @header("Pragma:no-cache\r\n");
        @header("Cache-Control:no-cache\r\n");
        @header("Expires:0\r\n");
    }

    function PutCookie($key, $value, $kptime = 0, $pa = "/")
    {
        global $cfg_cookie_encode, $cfg_domain_cookie;
        setcookie($key, $value, time() + $kptime, $pa, $cfg_domain_cookie);
        setcookie($key . '__ckMd5', substr(md5($cfg_cookie_encode . $value), 0, 16), time() + $kptime, $pa, $cfg_domain_cookie);
    }

    /**
     * +----------------------------------------------------------
     * 显示一级菜单
     * +----------------------------------------------------------
     */
    private function show_menu()
    {
        $cache = C('admin_big_menu');
        $count = count($cache);
        $i = 1;
        $menu = "";
        foreach ($cache as $url => $name)
        {
            if ($i == 1)
            {
                $css = $url == MODULE_NAME || !$cache[MODULE_NAME] ? "fisrt_current" : "fisrt";
                $menu .= '<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
            } else
            {
                if ($i == $count)
                {
                    $css = $url == MODULE_NAME ? "end_current" : "end";
                    $menu .= '<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
                } else
                {
                    $css = $url == MODULE_NAME ? "current" : "";
                    $menu .= '<li class="' . $css . '"><span><a href="' . U($url . '/index') . '">' . $name . '</a></span></li>';
                }
            }
            $i++;
        }
        return $menu;
    }



    /**
     * +----------------------------------------------------------
     * 显示二级菜单
     * +----------------------------------------------------------
     */
    private function show_sub_menu()
    {
        $big = MODULE_NAME == "Index" ? "Common" : MODULE_NAME;
        $cache = C('admin_sub_menu');
        $sub_menu = array();
        if ($cache[$big])
        {
            $cache = $cache[$big];
            foreach ($cache as $url => $title)
            {
                $url = $big == "Common" ? $url : "$big/$url";
                $sub_menu[] = array('url' => U("$url"), 'title' => $title);
            }
            return $sub_menu;
        } else
        {
            return $sub_menu[] = array('url' => '#', 'title' => "该菜单组不存在");
        }
    }

}